﻿using DX.IO;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DX
{
    class DefaultFileSystemDialog : IFileSystemDialog
    {

        public Task<FileEntry> OpenSingleFile(string filter)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = filter;
            dialog.Multiselect = false;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                return Task.FromResult(FileEntry.Physics(dialog.FileName));
            }
            return Task.FromResult<FileEntry>(null);

        }

        public Task<FileEntry[]> OpenMultipleFile(string filter)
        {

            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = filter;
            dialog.Multiselect = true;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                return Task.FromResult(dialog.FileNames.Select(FileEntry.Physics).ToArray());
            }
            return Task.FromResult(new FileEntry[0]);

        }

        public Task OpenSaveAs(FileEntry file, string filter="")
        {
            string tmpfilter = filter;
            if (string.IsNullOrEmpty(tmpfilter))
            {
                var ex = Path.GetExtension(file.Name);
                tmpfilter = $"{ex}|*{ex}";
            }

            SaveFileDialog dialog = new SaveFileDialog()
            {
                FileName = file.Name,
                Filter = tmpfilter,
            };
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                using var stream = dialog.OpenFile();
                var buffer = file.GetBuffer();
                stream.Write(buffer, 0, buffer.Length);
                stream.Flush();
            }
            return Task.CompletedTask;

        }
    }
}
